"""
简化的内存存储，用于测试
"""
from typing import List, Optional, Dict, Any
from datetime import datetime
import json

class SimpleStorage:
    """简单的内存存储"""
    
    def __init__(self):
        self.signal_collections: List[Dict[str, Any]] = []
        self.devices: List[Dict[str, Any]] = []
        self.next_id = 1
    
    async def create_signal_collection(self, signal_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建信号采集记录"""
        record = {
            "id": self.next_id,
            **signal_data,
            "uploaded_at": datetime.utcnow().isoformat(),
            "created_at": datetime.utcnow().isoformat(),
        }
        self.signal_collections.append(record)
        self.next_id += 1
        return record
    
    async def get_signal_collections(
        self, 
        device_id: Optional[str] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        limit: int = 100,
        offset: int = 0
    ) -> List[Dict[str, Any]]:
        """获取信号采集记录列表"""
        records = self.signal_collections.copy()
        
        if device_id:
            records = [r for r in records if r.get("device_id") == device_id]
        
        if start_time:
            records = [r for r in records if datetime.fromisoformat(r["collected_at"]) >= start_time]
        
        if end_time:
            records = [r for r in records if datetime.fromisoformat(r["collected_at"]) <= end_time]
        
        # 按时间倒序排列
        records.sort(key=lambda x: x["collected_at"], reverse=True)
        
        return records[offset:offset + limit]
    
    async def get_signal_statistics(self, device_id: str) -> Optional[Dict[str, Any]]:
        """获取设备信号统计信息"""
        device_records = [r for r in self.signal_collections if r.get("device_id") == device_id]
        
        if not device_records:
            return None
        
        signal_strengths = [r["signal_strength"] for r in device_records]
        collected_times = [datetime.fromisoformat(r["collected_at"]) for r in device_records]
        
        return {
            "device_id": device_id,
            "total_collections": len(device_records),
            "avg_signal_strength": sum(signal_strengths) / len(signal_strengths),
            "min_signal_strength": min(signal_strengths),
            "max_signal_strength": max(signal_strengths),
            "first_collection": min(collected_times).isoformat(),
            "last_collection": max(collected_times).isoformat(),
            "collection_days": len(set(d.date() for d in collected_times)),
        }
    
    async def register_device(self, device_info: Dict[str, Any]) -> Dict[str, Any]:
        """注册设备信息"""
        device_id = device_info["device_id"]
        
        # 检查设备是否已存在
        existing_device = next((d for d in self.devices if d["device_id"] == device_id), None)
        
        if existing_device:
            # 更新现有设备
            existing_device.update(device_info)
            existing_device["last_seen"] = datetime.utcnow().isoformat()
            existing_device["is_active"] = True
            existing_device["updated_at"] = datetime.utcnow().isoformat()
            return existing_device
        else:
            # 创建新设备
            new_device = {
                "id": self.next_id,
                **device_info,
                "last_seen": datetime.utcnow().isoformat(),
                "is_active": True,
                "created_at": datetime.utcnow().isoformat(),
                "updated_at": datetime.utcnow().isoformat(),
            }
            self.devices.append(new_device)
            self.next_id += 1
            return new_device

# 全局存储实例
storage = SimpleStorage()